<template>
  <div class="addUser">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="ruleForm.tel" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
        <el-button @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addUser } from "@/api/set";
import {isValidPhoneNumber} from "@/utils/validate";
export default {
  name: "addUser",
  data() {
    var validateTel = (rule, value, callback) => {
        if (value =='') {
          callback(new Error('请输入手机号'));
        } else {
          if (isValidPhoneNumber(value)) {
            callback();
          }else{
            callback(new Error('手机号格式错误'));
          }
        }
      };
    return {
      ruleForm: {
        name: "",
        password: "",
        tel:""
      },
      rules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        tel: [{ required: true,validator: validateTel, trigger: "blur" }],
      }
    };
  },
  mounted() {
    this.initial();
  },
  methods: {
    async initial() {},
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let result = await addUser(this.ruleForm);
          if(result.code == 200){
            this.$message({
              type: "success",
              message: "添加成功!"
            });
            this.$emit('sureAddUser');
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.addUser {
}
</style>
